 package com.ulook.lookplanet.ui.notifications.chat;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.service.UserMsgService;
import com.ulook.lookplanet.ui.notifications.VMsgUser;
import com.ulook.lookplanet.util.StringUtil;
import com.ulook.lookplanet.widget.MyMsgView;
import com.ulook.lookplanet.widget.YouMsgView;

import java.util.List;

public class ChatActivity extends AppCompatActivity {

    private ChatViewModel viewModel;
    private LinearLayout msgLayout;
    private EditText inputEdit;
    private Button sendBt;

    private LocalBroadcastManager localBroadcastManager;
    private UserChatMsgReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        viewModel = new ViewModelProvider(this).get(ChatViewModel.class);
        viewModel.getToastText().observe(this, s -> {
            Toast.makeText(ChatActivity.this, s, Toast.LENGTH_SHORT).show();
        });
        viewModel.getInitState().observe(this, initState -> {
            if(initState){
                Log.d("#####", "ChatActivity--initData");
                Log.d("#####", viewModel.getVMsgUser().toString());
                initData();
            }
        });

        Intent intent = getIntent();
        VMsgUser msgUser = (VMsgUser) intent.getSerializableExtra("VMsgUser");
        if(msgUser.getFromuser() == 0 || msgUser.getTouser() == 0){
            finish();
        }
        viewModel.setVMsgUser(msgUser);

        initTopBar();
        //initData();
        registerMsgReceive();

    }

    @Override
    protected void onDestroy() {
        unregisterMsgReceive();
        super.onDestroy();
    }

    private void initTopBar(){
        QMUITopBarLayout topBar = findViewById(R.id.chat_bar);
        topBar.addLeftBackImageButton().setOnClickListener(view -> {
            finish();
        });
        topBar.setTitle(viewModel.getVMsgUser().getFromname());
    }

    private void initData(){
        msgLayout = findViewById(R.id.chat_msg_layout);
        // 展示初始数据
        List<VMsgUser> history = viewModel.getHistoryMsg(4);
        List<VMsgUser> unread = viewModel.getUnreadMsg();
        for(int i = 0; i < history.size(); i++){
            if(history.get(i).getFromuser() == viewModel.getVMsgUser().getFromuser()){
                YouMsgView youMsgView = new YouMsgView(this);
                youMsgView.setHead(viewModel.getYouHead());
                youMsgView.setTime(history.get(i).getSendtime().subSequence(5, 16).toString());
                youMsgView.setMsg(history.get(i).getMsg());
                msgLayout.addView(youMsgView, 0);
            }else {
                MyMsgView myMsgView = new MyMsgView(this);
                myMsgView.setHead(viewModel.getMyHead());
                myMsgView.setTime(history.get(i).getSendtime().subSequence(5, 16).toString());
                myMsgView.setMsg(history.get(i).getMsg());
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.gravity = Gravity.END;  //这才是布局文件中的Android:layout_gravity属性
                myMsgView.setLayoutParams(lp);
                msgLayout.addView(myMsgView, 0);
            }
        }
        for(int i = 0; i < unread.size(); i++){
            YouMsgView youMsgView = new YouMsgView(this);
            youMsgView.setHead(viewModel.getYouHead());
            youMsgView.setTime(unread.get(i).getSendtime().subSequence(5, 16).toString());
            youMsgView.setMsg(unread.get(i).getMsg());
            msgLayout.addView(youMsgView);
        }
        // 发送按钮
        inputEdit = findViewById(R.id.chat_input_tx);
        sendBt = findViewById(R.id.chat_send_bt);
        sendBt.setOnClickListener(view -> {
            String msg = inputEdit.getText().toString();
            inputEdit.setText("");
            if(!StringUtil.isEmpty(msg)){
                // 发送消息
                VMsgUser vMsgUser = viewModel.sendMsg(msg);
                // 展示
                MyMsgView myMsgView = new MyMsgView(ChatActivity.this);
                myMsgView.setHead(viewModel.getMyHead());
                myMsgView.setTime(vMsgUser.getSendtime().subSequence(5, 16).toString());
                myMsgView.setMsg(vMsgUser.getMsg());
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.gravity = Gravity.END;  //这才是布局文件中的Android:layout_gravity属性
                myMsgView.setLayoutParams(lp);
                msgLayout.addView(myMsgView);
            }
        });
    }

    /**
     * 展示新数据
     */
    private void displayNewMsg(VMsgUser vMsgUser){
        YouMsgView youMsgView = new YouMsgView(this);
        youMsgView.setHead(viewModel.getYouHead());
        youMsgView.setTime(vMsgUser.getSendtime().subSequence(5, 16).toString());
        youMsgView.setMsg(vMsgUser.getMsg());
        msgLayout.addView(youMsgView);
        viewModel.updateMsgRead(vMsgUser.getUid());
    }

    /**
     * 注册MsgService的广播
     */
    private void registerMsgReceive(){
        Log.d("#####","ChatActivity--注册广播");
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        // 用户消息广播
        IntentFilter userFilter = new IntentFilter();
        userFilter.addAction(UserMsgService.INTENT_ACTION);
        receiver = new ChatActivity.UserChatMsgReceiver();
        localBroadcastManager.registerReceiver(receiver, userFilter);
    }

    /**
     * 注销广播
     */
    private void unregisterMsgReceive(){
        Log.d("#####", "ChatActivity--注销广播");
        localBroadcastManager.unregisterReceiver(receiver);
    }

    class UserChatMsgReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            VMsgUser vMsgUser = (VMsgUser) intent.getSerializableExtra("msg");
            //if(viewModel.getVMsgUser() != null){
            if(vMsgUser.getFromuser() == viewModel.getVMsgUser().getFromuser()){
                displayNewMsg(vMsgUser);
            }
            //}
        }
    }
}